package com.wanboedu.controller;

import com.aliyun.tea.*;
import com.aliyun.ocr_api20210707.models.*;
import com.aliyun.teaopenapi.models.Config;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.wanboedu.dto.InvoiceDTO;
import com.wanboedu.result.Result;
import darabonba.core.exception.TeaException;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.time.format.DateTimeFormatter;


@RestController
@RequestMapping("/admin/ocr")
@Slf4j
@Api("发票扫描")
public class OcrController {

    /**
     * <b>description</b> :
     * <p>使用AK&amp;SK初始化账号Client</p>
     *
     * @return Client
     * @throws Exception
     */
    public static com.aliyun.ocr_api20210707.Client createClient() throws Exception {
        // 工程代码泄露可能会导致 AccessKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考。
        // 建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/378657.html。
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
                .setAccessKeyId("LTAI5tJmNr4LycvZtJn9NKCw")
                // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
                .setAccessKeySecret("SIYDGNlX5XTba3y5kT8rlzqbA5ZH5A");
        // Endpoint 请参考 https://api.aliyun.com/product/ocr-api
        config.endpoint = "ocr-api.cn-hangzhou.aliyuncs.com";
        return new com.aliyun.ocr_api20210707.Client(config);
    }

    /**
     * 发票扫描
     * @param file
     * @return com.aliyun.ocr_api20210707.models.RecognizeInvoiceResponse
     */
    @PostMapping
    public Result ocr(@RequestParam("file") MultipartFile file) throws Exception {

        com.aliyun.ocr_api20210707.Client client = OcrController.createClient();
        // 需要安装额外的依赖库，直接点击下载完整工程即可看到所有依赖。
        java.io.InputStream bodyStream = file.getInputStream();
        com.aliyun.ocr_api20210707.models.RecognizeInvoiceRequest recognizeInvoiceRequest = new com.aliyun.ocr_api20210707.models.RecognizeInvoiceRequest()
                .setBody(bodyStream);
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            // 复制代码运行请自行打印 API 的返回值
            RecognizeInvoiceResponse response = client.recognizeInvoiceWithOptions(recognizeInvoiceRequest, runtime);
            RecognizeInvoiceResponseBody body = response.body;
            String data = body.data;
            Gson gson = new Gson();
            JsonElement jsonElement = gson.fromJson(data, JsonElement.class);

            // 将JSON对象转换为字符串
            String standardJson = gson.toJson(jsonElement);

            // 输出标准JSON格式
            System.out.println(standardJson);
            return Result.success(standardJson);
        } catch (TeaException error) {
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            System.out.println(error.getMessage());
            // 诊断地址

            com.aliyun.teautil.Common.assertAsString(error.getMessage());
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            System.out.println(error.getMessage());
            // 诊断地址
            com.aliyun.teautil.Common.assertAsString(error.getMessage());
        }
        return null;
    }


    /**
     * 发票验真
     * @param invoiceDTO
     * @return
     * @throws Exception
     */
    @PostMapping("/confirm")
    public Result confirm(@RequestBody InvoiceDTO invoiceDTO) throws Exception {
        log.info("发票验真：invoiceDTO:{}", invoiceDTO);
        Integer length = invoiceDTO.getCheckCode().length();
        String lastSixDigits = null;
        if (length >= 6) {
            lastSixDigits = invoiceDTO.getCheckCode().substring(length - 6);
            System.out.println(lastSixDigits);
        } else {
            System.out.println("字符串长度不足6位");
        }
        DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        // 将LocalDateTime对象格式化为新的字符串
        String formattedDateTimeStr = invoiceDTO.getInvoiceDate().format(outputFormatter);

        com.aliyun.ocr_api20210707.Client client = OcrController.createClient();
        com.aliyun.ocr_api20210707.models.VerifyVATInvoiceRequest verifyVATInvoiceRequest = new com.aliyun.ocr_api20210707.models.VerifyVATInvoiceRequest()
                .setInvoiceDate(formattedDateTimeStr)
                .setInvoiceCode(invoiceDTO.getInvoiceCode())
                .setInvoiceNo(invoiceDTO.getInvoiceNumber())
                .setInvoiceSum(invoiceDTO.getInvoiceAmountPreTax().toString())
                .setVerifyCode(lastSixDigits);
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            // 复制代码运行请自行打印 API 的返回值
            VerifyVATInvoiceResponse response = client.verifyVATInvoiceWithOptions(verifyVATInvoiceRequest, runtime);
            VerifyVATInvoiceResponseBody body = response.body;
            String data = body.data;
            return Result.success(data);
        } catch (TeaException error) {
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            com.aliyun.teautil.Common.assertAsString(error.getMessage());
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            System.out.println(error.getMessage());
            com.aliyun.teautil.Common.assertAsString(error.getMessage());
        }
        return null;
    }

}
